package com.sp.writer_;

import java.io.FileWriter;
import java.io.IOException;

/**
 * 使用FileWriter类, 将 "风雨之后, 定见彩虹" 写入到 story.txt 文件中
 */
public class FileWriter_ {
    public static void main(String[] args) {
        FileWriter fileWriter = null;
        String filePath = "d:\\development\\code\\IO_Test\\news\\story.txt";
        String str = "风雨之后, 定见彩虹";
        char[] chars = {'a', 'b', 'c'};

        try {
            fileWriter = new FileWriter(filePath);

            //write(int): 写入单个字符
//            fileWriter.write('H');
            //write(char[]): 写入指定数组
//            fileWriter.write(chars);
            //write(char[], off, len): 写入字符数组的一部分
//            fileWriter.write(chars, 1,2);
            //write(String)
//            fileWriter.write(str);
            //write(String, off, len): 写入字符串指定部分
            fileWriter.write(str, 2, 5);
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //对于FileWriter, 一定要关闭流, 或者Flush才能真正的将数据写入到文件中
            try {
                if (fileWriter != null){
//                    fileWriter.flush();
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
